﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.ModelBinding.Binders;

namespace VisionCloud.Domain.Binder
{
    class GuidModelBinder : IModelBinder
    {
        private readonly IGuidAttribute _guidAttribute;

        private readonly SimpleTypeModelBinder _simpleTypeModelBinder;

        public GuidModelBinder(Type type, IGuidAttribute guidAttribute)
        {
            if (type == null)
            {
                throw new ArgumentNullException(nameof(type));
            }

            _guidAttribute = guidAttribute;

            _simpleTypeModelBinder = new SimpleTypeModelBinder(type);
        }

        public Task BindModelAsync(ModelBindingContext modelBindingContext)
        {
            if (modelBindingContext == null)
            {
                throw new ArgumentNullException(nameof(modelBindingContext));
            }

            var valueProviderResult = modelBindingContext.ValueProvider.GetValue(modelBindingContext.ModelName);

            if (valueProviderResult != ValueProviderResult.None)
            {
                modelBindingContext.ModelState.SetModelValue(modelBindingContext.ModelName, valueProviderResult);

                var value = valueProviderResult.FirstValue;

                bool success;

                var result = _guidAttribute.Guid(value, out success);

                if (success)
                {
                    modelBindingContext.Result = ModelBindingResult.Success(result);

                    return Task.CompletedTask;
                }
            }

            return _simpleTypeModelBinder.BindModelAsync(modelBindingContext);
        }
    }
}
